package com.example.demo.lc;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 二叉树的右视图
 * @Author wzh
 * @Date 2021/10/19 2:59 下午
 * @Version 1.0
 * https://leetcode-cn.com/problems/binary-tree-right-side-view/
 */
public class Leetcode199 {
    static List<Integer> result = new ArrayList<>();

    public static void main(String[] args) {
        result = new ArrayList<>();

        TreeNode treeNode5 = new TreeNode(5);
        TreeNode treeNode2 = new TreeNode(2,null,treeNode5);
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode3 = new TreeNode(3,null,treeNode4);
        TreeNode treeNode1 = new TreeNode(1,treeNode2,treeNode3);

        System.out.println(rightSideView(treeNode1));
    }

    public static List<Integer> rightSideView(TreeNode root) {
        dfs(root,0);
        return result;
    }

    private static void dfs(TreeNode root,int length) {
        if(root == null){
            return;
        }
        if(length == result.size()){
            result.add(root.val);
        }
        length++;
        if(root.right != null)dfs(root.right,length);
        if(root.left != null)dfs(root.left,length);
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}



